package com.haofengsoft.scce.ui.consultation;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.haofengsoft.platform.utils.EquipmentUtil;
import com.haofengsoft.scce.R;
import com.haofengsoft.scce.common.client.VolleyBean;
import com.haofengsoft.scce.common.client.VolleyInterface;
import com.haofengsoft.scce.common.client.VolleyManage;
import com.haofengsoft.scce.common.config.ConstantConfig;
import com.haofengsoft.scce.db.bean.UserInfo;
import com.haofengsoft.scce.db.biz.CollectingOperLogBiz;
import com.haofengsoft.scce.db.cache.UserCache;
import com.haofengsoft.scce.db.entity.CollectingOperLog;
import com.haofengsoft.scce.dialog.NoLoginPromptDialog;
import com.haofengsoft.scce.popupwin.CommentPopWinInterface;
import com.haofengsoft.scce.popupwin.CommentPopupWindow;

/**
 * Created by admin on 2015/7/20.
 */
public class ConsultationDetailActivity extends Activity {
	private WebView ptrWv;
	private WebSettings settings;
	private ToggleButton textSizeTogBtn;
	private String sourceUrl;
	private UserInfo userInfo;
	private String title;
	private String newsId;
	private String general;
	private ProgressBar progressBar;

	private String commnentContent = null;
	private int modelType = 1;// 消息类型，先定义一个
	private CollectingOperLog collectingOperLog = null;
	private TextView contectTv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.consultation_detail);
		ImageView backIv = (ImageView) findViewById(R.id.consultation_detail_back_iv);
		backIv.setOnClickListener(new BackOnClickListener());
		userInfo = UserCache.getInstance().getUser(ConsultationDetailActivity.this);

		Intent fromIntent = getIntent();
		title = fromIntent.getStringExtra("title");
		String time = fromIntent.getStringExtra("time");
		String source = fromIntent.getStringExtra("source");
		sourceUrl = fromIntent.getStringExtra("sourceUrl");
		sourceUrl = sourceUrl + "&time=" + Calendar.getInstance().getTimeInMillis();
		newsId = fromIntent.getStringExtra("newsId");

		collectingOperLog = CollectingOperLogBiz.getInstance(ConsultationDetailActivity.this)
				.gainCollectingOperLogByTypeWithId(modelType, Long.parseLong(newsId));
		general = fromIntent.getStringExtra("general");
		progressBar = (ProgressBar) findViewById(R.id.consultation_detail__progress_pb);
		ptrWv = (WebView) findViewById(R.id.consultation_detail_content_ptrwv);
		textSizeTogBtn = (ToggleButton) findViewById(R.id.consultation_detail_textsize_togbtn);
		textSizeTogBtn.setOnCheckedChangeListener(new TextSizeOnCheckedChangeListener());
		TextView shareTv = (TextView) findViewById(R.id.consultation_detail_share_tv);
		shareTv.setOnClickListener(new ShareOnClickListener());

		contectTv = (TextView) findViewById(R.id.consultation_detail_contect_tv);
		if (collectingOperLog == null) {
			contectTv.setText("收藏");
		} else {
			contectTv.setText("取消收藏");
		}
		contectTv.setOnClickListener(new ContectClickListener());
		TextView feedBackTv = (TextView) findViewById(R.id.consultation_detail_feedback_tv);
		feedBackTv.setOnClickListener(new FeedBackClickListener());
		settings = ptrWv.getSettings();
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);
		settings.setDefaultTextEncodingName("UTF-8");
		settings.setDefaultFontSize(18);
		ptrWv.setWebViewClient(new SampleWebViewClient());
		ptrWv.loadUrl(sourceUrl);

	}

	public class BackOnClickListener implements View.OnClickListener {
		@Override
		public void onClick(View view) {
			finish();
		}
	}

	class ContectClickListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			// 收藏
			contectTv.setEnabled(false);
			progressBar.setVisibility(View.VISIBLE);
			if (collectingOperLog == null) {
				// 收藏
				Map<String, Object> mapParam = new HashMap<String, Object>();
				mapParam.put("NewsID", newsId);
				mapParam.put("ColEmpID", EquipmentUtil.deviceId(ConsultationDetailActivity.this));
				VolleyManage.getInstance().methodPost(ConsultationDetailActivity.this, null,
						ConstantConfig.COMMENT_CONSULTATION_URL, mapParam, new CollectionVolleyReal());
			} else {
				// 取消收藏
				Map<String, Object> mapParam = new HashMap<String, Object>();
				mapParam.put("NewsID", newsId);
				mapParam.put("ColEmpID", EquipmentUtil.deviceId(ConsultationDetailActivity.this));
				VolleyManage.getInstance().methodPost(ConsultationDetailActivity.this, null,
						ConstantConfig.COMMENT_CONSULTATION_CANCEL_URL, mapParam, new CancelCollectionVolleyReal());
			}

		}
	}

	class CancelCollectionVolleyReal implements VolleyInterface {

		@Override
		public void gainData(VolleyBean bean) {
			progressBar.setVisibility(View.GONE);
			contectTv.setEnabled(true);
			if (bean.isSuccess()) {
				contectTv.setText("收藏");
				CollectingOperLogBiz.getInstance(ConsultationDetailActivity.this).deleteById(collectingOperLog.getId());
				collectingOperLog = null;
			}
		}
	}

	class CollectionVolleyReal implements VolleyInterface {

		@Override
		public void gainData(VolleyBean bean) {
			progressBar.setVisibility(View.GONE);
			contectTv.setEnabled(true);
			if (bean.isSuccess()) {
				contectTv.setText("取消收藏");
				CollectingOperLogBiz.getInstance(ConsultationDetailActivity.this).insertCollectingOperLog(modelType,
						Long.parseLong(newsId));
				collectingOperLog = CollectingOperLogBiz.getInstance(ConsultationDetailActivity.this)
						.gainCollectingOperLogByTypeWithId(modelType, Long.parseLong(newsId));
				Toast.makeText(ConsultationDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ConsultationDetailActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
			}
		}

	}

	class FeedBackClickListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			// 评论
			CommentPopupWindow feedBackPopupWindow = new CommentPopupWindow(ConsultationDetailActivity.this,
					new CommentPopWinReal());
			feedBackPopupWindow.showAtLocation(
					ConsultationDetailActivity.this.findViewById(R.id.consultation_detail_rl), Gravity.BOTTOM
							| Gravity.CENTER_HORIZONTAL, 0, 0);
		}
	}

	class CommentPopWinReal implements CommentPopWinInterface {

		@Override
		public void commentContent(String contentValue) {
			commnentContent = contentValue;
			if (userInfo.getId() == -1) {
				NoLoginPromptDialog dialog = new NoLoginPromptDialog(ConsultationDetailActivity.this);
				dialog.show();
			} else {
				progressBar.setVisibility(View.VISIBLE);
				// 发表评论
				commentSubmit(contentValue);
			}
		}
	}

	private void commentSubmit(String contentValue) {
		Map<String, Object> mapParam = new HashMap<String, Object>();
		mapParam.put("NewsID", newsId);
		mapParam.put("UserID", userInfo.getId());
		mapParam.put("Contents", contentValue);
		VolleyManage.getInstance().methodPost(ConsultationDetailActivity.this, null, ConstantConfig.COMMENT_SUBMIT_URL,
				mapParam, new CommentVolleyReal());
	}

	class CommentVolleyReal implements VolleyInterface {

		@Override
		public void gainData(VolleyBean bean) {
			progressBar.setVisibility(View.GONE);
			if (bean.isSuccess()) {
				Toast.makeText(ConsultationDetailActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ConsultationDetailActivity.this, bean.getMessage(), Toast.LENGTH_SHORT).show();
			}
		}

	}

	class TextSizeOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
			textSizeTogBtn.setChecked(b);
			if (b) {
				settings.setDefaultFontSize(22);
			} else {
				settings.setDefaultFontSize(18);
			}
		}
	}

	private static class SampleWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}
	}

	class ShareOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View view) {
			showShare();
		}
	}

	private void showShare() {
		ShareSDK.initSDK(ConsultationDetailActivity.this);
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		//
		// // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
		// //oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		// oks.setTitle(getString(R.string.share));
		// // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		// oks.setTitleUrl("http://sharesdk.cn");
		// // text是分享文本，所有平台都需要这个字段
		// oks.setText("我是邮品汇");
		// // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
		// // url仅在微信（包括好友和朋友圈）中使用
		// oks.setUrl("http://sharesdk.cn");
		// // comment是我对这条分享的评论，仅在人人网和QQ空间使用
		// oks.setComment("邮品汇上线啦");
		// // site是分享此内容的网站名称，仅在QQ空间使用
		// oks.setSite(getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		// oks.setSiteUrl("http://www.haofengsoft.com");
		// oks.setText("逛邮市上线啦");
		// oks.setTitle("逛邮市");
		// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
		// oks.setUrl("http://www.guangyoushi.cn");
		oks.setTitle(title);
		oks.setTitleUrl(sourceUrl);
		oks.setText(general);
		oks.setImageUrl("http://sj.haofengsoft.com/images/108_logo.png");
		oks.setUrl(sourceUrl);
		// 启动分享GUI
		oks.show(ConsultationDetailActivity.this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		userInfo = UserCache.getInstance().getUser(ConsultationDetailActivity.this);
		if (null != commnentContent) {
			commentSubmit(commnentContent);
		}
	}
}